﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MvcTricks.RoundTripModelBinding.Serialization;
using System.Web.Script.Serialization;

namespace MvcTricks.RoundTripModelBinding.Testing
{
    [TestClass]
    public class CustomTypeSerializerTests
    {
        [TestMethod]
        public void Can_use_a_custom_object_serializer()
        {
            Configuration.Default = new Configuration(StorageModes.CompressAndEncrypt, new JavaScriptConverter[] { new CustomBooleanClassObjectSerializer() });
            var model = new CustomBooleanClass() { Value = true };
            var serialized = ModelData.Serialize(model);
            var deserialized = ModelData.Deserialize<CustomBooleanClass>(serialized);
            Assert.AreEqual(model.Value, deserialized.Value);
        }

        public class CustomBooleanClass
        {
            public bool Value { get; set; }
        }

        public class CustomBooleanClassObjectSerializer : JavaScriptConverter
        {

            public override IEnumerable<Type> SupportedTypes
            {
                get { return new Type[] { typeof(CustomBooleanClass) }; }
            }

            public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
            {
                Dictionary<string, object> result = new Dictionary<string, object>();
                if (obj != null)
                {
                    CustomBooleanClass value = (CustomBooleanClass)obj;
                    result["Value"] = ((value.Value) ? "x" : "y");
                }
                else
                    result["Value"] = null;
                return result;
            }

            public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
            {
                if (dictionary == null)
                    throw new ArgumentNullException("dictionary");

                if (type == typeof(CustomBooleanClass))
                {
                    var value = new CustomBooleanClass() { Value = (((string)dictionary["Value"] == "x") ? true : false) };
                    return value;
                }
                return null;
            }

        }

    }
}
